package com.mtw.bbs.reply.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.feign.ArticleClient;
import com.mtw.bbs.article.pojo.vo.SimpleArticleVo;
import com.mtw.bbs.common.core.constant.FileConstant;
import com.mtw.bbs.common.core.enums.ResultCode;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.util.BeanCopyUtils;
import com.mtw.bbs.common.core.util.FileUtil;
import com.mtw.bbs.common.core.vo.BaseFileVo;
import com.mtw.bbs.constant.ReplyTypeEnum;
import com.mtw.bbs.like.service.LikeProviderService;
import com.mtw.bbs.reply.job.ReplyAsyncJob;
import com.mtw.bbs.reply.pojo.dto.ReplyDto;
import com.mtw.bbs.reply.pojo.entity.ReplyIndex;
import com.mtw.bbs.reply.pojo.form.ReplyForm;
import com.mtw.bbs.reply.pojo.vo.ReplyVo;
import com.mtw.bbs.reply.service.ReplyIndexService;
import com.mtw.bbs.common.core.constant.BusinessObjectType;
import com.mtw.bbs.common.core.enums.SortEnum;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 用户评论
 */
@RestController
@RequestMapping("user/reply")
@RequiredArgsConstructor
public class UserReplyController {

    private final UserClient userClient;
    private final ArticleClient articleClient;
    private final ReplyAsyncJob replyAsyncJob;
    private final ReplyIndexService replyIndexService;
    private final LikeProviderService likeProviderService;


    /**
     * 当前用户发布的评论
     *
     * @param page 当前页
     * @param size 分页大小
     * @param sort 排序方式
     */
    @GetMapping("/getList/{type}")
    public Result getCurrentUserArticleReply(@PathVariable(name = "type") int type,
                                             @RequestParam(name = "page") int page,
                                             @RequestParam(name = "size") int size,
                                             @RequestParam(name = "sort", required = false) Integer sort) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }

        String businessObjectType = ReplyTypeEnum.getBusinessObjectType(type);
        if (StringUtils.isBlank(businessObjectType)){
            return Result.fail(ResultCode.PARAM_ERROR);
        }

        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.eq("r.created_by", details.getId());
        qw.eq("r.object_type", businessObjectType);
        if (SortEnum.SORT_LIKE.getCode().equals(sort)) {
            qw.orderByDesc("ri.like_count");
        } else {
            qw.orderByDesc("r.created_date");
        }

        Page<ReplyDto> dtoPage = replyIndexService.getUserReplyVoPage(page, size, details.getId(), qw);

        Page<ReplyVo> voPage = new Page<>(page, size, dtoPage.getTotal());

        if (ReplyTypeEnum.ARTICLE_REPLY.getCode().equals(type)){
            this.setArticleInfo(voPage,dtoPage,details);
        }

        return Result.success(voPage);
    }


    /**
     * 填充文章信息
     */
    private void setArticleInfo(Page<ReplyVo> voPage,Page<ReplyDto> dtoPage,UserDetails details){

        if (!dtoPage.getRecords().isEmpty()) {
            // 获取当前用户
            Result<UserInfoVo> userResult = userClient.getUserVoByUsername(details.getUsername());
            UserInfoVo userInfoVo;
            if (userResult.isSuccess() && userResult.getData() != null) {
                userInfoVo = userResult.getData();
            } else {
                userInfoVo = null;
            }
            // 查文章
            Map<String, SimpleArticleVo> articleMap = new HashMap<>(0);
            Result<List<SimpleArticleVo>> articleResult = articleClient.getArticleById(dtoPage.getRecords().stream().map(ReplyDto::getObjectId).toArray(String[]::new));
            if (articleResult.isSuccess()) {
                articleMap = articleResult.getData().stream().collect(Collectors.toMap(SimpleArticleVo::getId, Function.identity()));
            }

            Map<String, SimpleArticleVo> finalArticleMap = articleMap;
            List<ReplyVo> voList = dtoPage.getRecords().stream().map(x -> {
                ReplyVo vo = BeanCopyUtils.copyBean(x, ReplyVo.class);
                vo.setPoster(userInfoVo);
                vo.setObjectInfo(this.setFileInfo(finalArticleMap.get(x.getObjectId())));
                return vo;
            }).toList();
            voPage.setRecords(voList);
        }
    }


    /**
     * 设置文章信息
     */
    private SimpleArticleVo setFileInfo(SimpleArticleVo vo) {
        if (vo == null || CollectionUtil.isEmpty(vo.getFileList())) {
            return vo;
        }
        BaseFileVo file = vo.getFileList().get(0);
        for (BaseFileVo x : vo.getFileList()) {
            Integer type = FileUtil.getTypeByFile(x.getFileSuffix());
            if (FileConstant.FILE_VIDEO.equals(type)) {
                file = x;
                break;
            }
        }
        vo.setFileList(Arrays.asList(file));
        return vo;
    }


    /**
     * 获取点赞的文章评论
     *
     * @param page 当前页
     * @param size 分页大小
     */
    @GetMapping("/like/{type}")
    public Result getArticleReplyByLike(@PathVariable(name = "type") int type,
                                        @RequestParam(name = "page") int page,
                                        @RequestParam(name = "size") int size) {


        UserDetails details = SecurityContextHolder.getContext().getAuthentication();

        String businessObjectType = ReplyTypeEnum.getBusinessObjectType(type);
        if (StringUtils.isBlank(businessObjectType)){
            return Result.fail(ResultCode.PARAM_ERROR);
        }

        //  查询已点赞的评论id
        List<String> listResult = likeProviderService.getUserLikeList(details.getId(), page, size, BusinessObjectType.REPLY);

        if (CollectionUtil.isEmpty(listResult)) {
            return Result.success(new Page<>(page, size, 0));
        }

        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.in("r.id", listResult);
        Page<ReplyVo> voPage = replyIndexService.getReplyVoPage(qw, SortEnum.SORT_TIME.getCode(), page, size);
        if (CollectionUtil.isNotEmpty(voPage.getRecords())) {
            // 查文章
            if (ReplyTypeEnum.ARTICLE_REPLY.getCode().equals(type)){
                Map<String, SimpleArticleVo> articleMap = new HashMap<>(0);
                Result<List<SimpleArticleVo>> articleResult = articleClient.getArticleById(voPage.getRecords().stream().map(ReplyVo::getObjectId).toArray(String[]::new));
                if (articleResult.isSuccess()) {
                    articleMap = articleResult.getData().stream().collect(Collectors.toMap(SimpleArticleVo::getId, Function.identity()));
                }
                Map<String, SimpleArticleVo> finalArticleMap = articleMap;
                voPage.getRecords().forEach(x -> x.setObjectInfo(this.setFileInfo(finalArticleMap.get(x.getObjectId()))));
            }
        }
        return Result.success(voPage);
    }


    /**
     * 保存评论
     */
    @PostMapping("/article")
    public Result saveArticleReply(@RequestBody ReplyForm form) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        try {
            if (StringUtils.isBlank(form.getRootId())) {
                form.setRootId("0");
            }
            if (StringUtils.isBlank(form.getParentId())) {
                form.setParentId("0");
            }
            // 回复自己
            if (details.getUsername().equals(form.getRepostedUserId()) && form.getRootId().equals(form.getParentId())) {
                form.setRepostedUserId(null);
            }
            form.setObjectType(BusinessObjectType.ARTICLE);
            ReplyIndex index = replyIndexService.saveReply(form);
            if (index != null) {
                form.setId(index.getId());
                replyAsyncJob.updateReplyCount(form, 1);
                return Result.success();
            } else {
                return Result.fail("发布失败");
            }
        } catch (BusinessException e) {
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public Result deleteComment(@PathVariable String id) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        ReplyIndex entity = replyIndexService.getById(id);
        if (entity == null) {
            return Result.fail("评论已删除");
        }
        boolean result = replyIndexService.deleteReplyByUserId(id, details.getId());
        if (result) {
            ReplyForm form = new ReplyForm();
            form.setId(id);
            form.setObjectId(entity.getObjectId());
            form.setObjectType(entity.getObjectType());
            replyAsyncJob.updateReplyCountByDelete(form);
            return Result.success();
        } else {
            return Result.fail("删除失败");
        }
    }


}
